4  便利なRの機能

便利だが普段はあまりつかわないため忘れがちな点についてメモしておく.

4.1 関数の中身を確認する

mean()関数がどのようにして作成されているのかを確認したい場合,meanのように()をとって入力すればよい.しかし,UseMethod("mean")のように関数が表示され,中身を確認できない場合もある.

mean
function (x, ...) 
UseMethod("mean")
<bytecode: 0x125593398>
<environment: namespace:base>

このような場合は,methods()関数を用いるとよい

methods(mean)
[1] mean.Date*     mean.default*  mean.difftime* mean.POSIXct*  mean.POSIXlt* 
[6] mean.quosure* 
see '?methods' for accessing help and source code

.様々な結果が示されるがここでは,2めの要素にあるmean.default*を確認しよう.*をとってmean.defaultと入力するだけでよい.

mean.default
function (x, trim = 0, na.rm = FALSE, ...) 
{
    if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
        warning("argument is not numeric or logical: returning NA")
        return(NA_real_)
    }
    if (isTRUE(na.rm)) 
        x <- x[!is.na(x)]
    if (!is.numeric(trim) || length(trim) != 1L) 
        stop("'trim' must be numeric of length one")
    n <- length(x)
    if (trim > 0 && n) {
        if (is.complex(x)) 
            stop("trimmed means are not defined for complex data")
        if (anyNA(x)) 
            return(NA_real_)
        if (trim >= 0.5) 
            return(stats::median(x, na.rm = FALSE))
        lo <- floor(n * trim) + 1
        hi <- n + 1 - lo
        x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi]
    }
    .Internal(mean(x))
}
<bytecode: 0x105dc2858>
<environment: namespace:base>